# -*- encoding:utf8 -*-
"""
利用read_attend_record_from_excel(path)返回考勤记录列表
返回的格式见 get_attend_list()文档

"""
import re
from datetime import datetime
import xlrd
from attendance.convert import t2i,str2date
from attendance.tool_func import get_or_none
from staff.models import StaffInfo
from attendance.date_func import month_finalday
from recordproc import record
from reportproc import report

def input_excel(filename=None, file_contents=None):
    """
    1 导入考勤原始记录excel
    2 处理考勤原始记录，
    3 并且将记录保存在数据库

    Args:
    @file_contents: 考勤excel03.xls文件的二进制内容
    
    考勤文件应该是xls格式，内容应该是:
    ['考勤号','姓名','部门','日期','打卡记录']
    经过read_attend_record_from_excel()函数分解，排序，返回的record_row格式为：
       {
        'attend_no': char 考勤号,
        'date': 考勤日期,
        'timestr':原始打卡记录
       }

    """
    tmp_attend_no=None
    staff=None
    datelist=set()
    stafflist=[]
    for record_row in read_attend_record_from_excel(filename=filename, file_contents=file_contents):
        attend_no = record_row['attend_no']
        if attend_no!=tmp_attend_no: 
            # 表示处理换人了
            tmp_attend_no=attend_no
            staff = get_or_none(StaffInfo, attend_no=attend_no)
            if staff:
                stafflist.append(staff)
                
        date = record_row['date']
        datelist.add(date)      
        timestr = record_row['timestr']
        
        if not staff:  # 如果找不到对应员工，则跳过处理
            continue
        workshift = staff.workshift
        if not workshift:  # 如果workshift是空，不做处理
            continue
        worktype = 'FTE' if staff.job_nature == 'L' else 'not_FTE',

        record(staff, date=str2date(date), timestr=timestr)
    monthlist=set()
    for dt in datelist:
        obj = str2date(dt)
        final = month_finalday(obj)
        monthlist.add(final)
    for monthfinalday in monthlist:
        for mystaff in stafflist:
            report(mystaff,monthfinalday)


def read_attend_record_from_excel(filename=None, file_contents=None):
    """ 生成器，一次返回一个考勤对象列表。
    
    Args:
    @filename:考勤原始记录的excel03文件路径。
    @file_contents ：直接传递文件内容
    
    二者传一个
    
    return:
    {
        'attend_no':考勤号,
        'date': 考勤日期,
        'timestr':原始打卡记录
    }
    
    注意，返回的元素是按照(考勤号,日期)排序的。
    """
    attendlist = read_excel_03(filename=filename, file_contents=file_contents)
    attendlist.sort(cmp=attend_sort_cmp)

    # 按照员工的考勤号，分组批量输出
    outlist = []
    last_attend_number = ''
    for row in attendlist:
        if row[3]:
            date = datetime.strptime(row[3], '%Y/%m/%d').date().strftime('%Y-%m-%d')
        else:
            date = ''

        record = {
            'attend_no': row[0],
            'date': date,
            'timestr': row[4]
        }
        yield record


def read_excel_03(filename=None, file_contents=None):
    "读取excel03的第一个sheet,以列表返回"
    rawdata = xlrd.open_workbook(filename=filename, file_contents=file_contents, encoding_override='gbk')
    table = rawdata.sheets()[0]
    nrows = table.nrows
    attendlist = []
    for i in range(1, nrows):
        attendlist.append(table.row_values(i))
    return attendlist


def attend_sort_cmp(x, y):
    """考勤列表排序
    x or y = ['考勤号','姓名','部门','日期','打卡记录']
    """
    if x[0] != y[0]:
        return cmp(x[0], y[0])
    else:
        xdate = datetime.strptime(x[3], "%Y/%m/%d").date()
        ydate = datetime.strptime(y[3], "%Y/%m/%d").date()
        return cmp(xdate, ydate)


if __name__ == '__main__':
    for i in get_attend_list(r"D:\work\attendance\attendance record.xls"):
        print(i)
